$(function() {



    window.treeGraph = null;
    const { TreeGraph, Grid, Menu, Tooltip, ToolBar, Minimap, Util, registerNode, registerEdge } = window.G6;
    const baseConfig = {
        nodePaddingLeft: 10,
        nodePaddingRight: 10,
        nameFontSize: 12,
        childCountWidth: 22,
        countMarginLeft: 10,
        nodeMinWidth: 50,
        countWidth: 10
    };

    // 创建绘制对象
    window.createGraph = {
        init() {
            this.initGraph();

            return {
                treeGraph,
            };
        },
        // 创建各类可插拔插件以及树形图对象
        initGraph() {
            const container = $('#container')[0];
            const grid = new Grid();
            const minimap = new Minimap({
                size: [200, 150],
                delegateStyle: {
                    fill: "red"
                }
            });
            const menu = this.createMenu();
            const tooltip = this.createTooltip();
            const toolbar = this.createToolbar();
            this.registerNode();
            this.registerEdge();
            treeGraph = new TreeGraph({
                container,
                width: container.offsetWidth,
                height: 900,
                modes: {
                    default: ['drag-canvas', {
                        type: "scroll-canvas",
                        zoomKey: 'ctrl'
                    }, {
                        type: 'collapse-expand',
                        trigger: 'click',
                    }],

                    edit: ['drag-canvas', {
                        type: "scroll-canvas",
                        zoomKey: 'ctrl'
                    }]
                },
                defaultNode: {
                    type: 'treeNode',
                    anchorPoints: [
                        [0, 0.5],
                        [1, 0.5],
                    ],
                },
                defaultEdge: { //绘制边
                    type: 'smoothEdge', //折线
                    style: {
                        stroke: '#DC143C', //边的颜色
                    },
                },
                layout: {
                    type: 'mindmap',
                    direction: 'LR',
                    getHeight() {
                        return 16;
                    },
                    getWidth(d) {
                        const labelWidth = Util.getTextSize(String(d.label), 12)[0];
                        const width = labelWidth + baseConfig.nodePaddingLeft + baseConfig.nodePaddingRight + 40;
                        return width;
                    },
                    getVGap() {
                        return 25;
                    },
                    getHGap() {
                        return 60;
                    },
                },
                plugins: [grid, minimap, menu, tooltip, toolbar],
            });
        },
        createMenu() {
            return new Menu({
                //是否允许 menu 出现，可以根据 evt.item（当前鼠标事件中的元素） 或 evt.target（当前鼠标事件中的图形）的内容判断此时是否允许 menu 出现
                shouldBegin(e) {
                    //if (e.item.getModel().Recid == 1) return false;
                    return true;
                },
                //菜单项内容， 支持 DOM 元素或字符串
                getContent(e) {

                    // 节点
                    let menus = '';

                    // 右键菜单命令
                    const commands = [{
                        command: 'appendItem',
                        name: '新增节点',
                    }, {
                        command: 'setToRoot',
                        name: '作为根节点查看',
                    }, {
                        command: 'deleteItem',
                        name: '删除节点',
                    }];

                    commands.forEach(item => {
                        menus += `<p class="menu-item" style="" command="${item.command}">${item.name}</p>`;
                    });

                    return menus;
                },
                //点击菜单项的回调函数
                handleMenuClick(target, item) {
                    const command = target.getAttribute('command');
                    graphMenuCallBack[command] && graphMenuCallBack[command](item);
                },
            });
        },
        createTooltip() {
            return new Tooltip({
                offsetX: 30,
                offsetY: -20,
                itemTypes: ['node'],
                shouldBegin(e) {
                    return true;
                },
                getContent(e) {
                    const model = e.item.getModel();
                    let html = "";

                    if (model.Recid == "1") {
                        html = model.TaskName;
                    } else {
                        html = model.WorkContent;
                    };
                    return html;
                },
            });
        },
        createToolbar() {
            return new ToolBar({
                getContent() {
                    /* 这里必须是 ul li */
                    return `
                  <ul class="graph-toolbar">
                    <li class="iconfont icon-zoom-in" code="zoomIn" title="放大"></li>
                    <li class="iconfont icon-zoom-out" code="zoomOut" title="缩小"></li>
                    <li class="iconfont icon-1x" code="defaultSize" title="1倍大小"></li>
                    <li class="iconfont icon-reset" code="relocation" title="重定位"></li>
                    <li class="iconfont icon-why" code="graphHelp" title="帮助"></li>
                </ul>
              `;
                },
                handleClick: (code) => {
                    console.log(code);
                    toolbarCallBack[code] && toolbarCallBack[code]();
                },
            });
        },
        registerNode() {
            registerNode(
                'treeNode', {
                    /**
                     * 绘制节点，包含文本
                     * @param  {Object} cfg 节点的配置项
                     * @param  {G.Group} group 图形分组，节点中的图形对象的容器
                     * @return {G.Shape} 绘制的图形，通过 node.get('keyShape') 可以获取到
                     */
                    draw(cfg, group) {
                        // console.log(Util);
                        const { label, isRoot, children } = cfg;
                        const rootNode = isRoot === 0;
                        const height = 28;
                        const countWidth = 22;
                        const textWidth = Util.getTextSize(String(label), 12)[0];
                        const nodeWidth =
                            baseConfig.nodePaddingLeft +
                            textWidth +
                            baseConfig.nodePaddingRight +
                            (children && children.length ? countWidth : 0) +
                            10;
                        const isRight = cfg.x > 0;
                        const keyShapeAttrs = {
                            width: nodeWidth,
                            height,
                            x: 0,
                            y: 0,
                            radius: 15,
                            cursor: 'pointer',
                        };
                        const keyShape = group.addShape('rect', {
                            attrs: keyShapeAttrs,
                            name: 'root-key-shape-rect-shape',
                        });

                        group.addShape('rect', {
                            attrs: {
                                x: 0,
                                y: 0,
                                width: nodeWidth,
                                height,
                                fill: '#e8f7ff',
                                cursor: 'pointer',
                                shadowColor: "#C0C0C0",
                                shadowBlur: 10,
                                shadowOffsetX: 5,
                                shadowOffsetY: 5,
                                radius: 14,
                                opacity: 1,
                            },
                            name: 'main-shape',
                        });


                        group.addShape('text', {
                            attrs: {
                                text: label,
                                textAlign: 'left',
                                textBaseline: 'top',
                                fill: '#222',
                                fontSize: 12,
                                cursor: 'pointer',
                                x: 10,
                                y: 8,
                            },
                            name: 'not-root-text-shape',
                        });


                        if (children && children.length > 0) {
                            // 添加子节点数量
                            const countHeight = 12;

                            group.addShape('rect', {
                                attrs: {
                                    width: countWidth,
                                    height: countHeight,
                                    radius: 6,
                                    stroke: '#5CDBD3',
                                    fill: '#E6FFFB',
                                    x: nodeWidth + baseConfig.countWidth,
                                    y: 8,
                                },
                            });

                            group.addShape('text', {
                                attrs: {
                                    fill: '#222',
                                    fontSize: 10,
                                    cursor: 'pointer',
                                    textAlign: 'center',
                                    width: baseConfig.countWidth,
                                    text: `${children?.length}`,
                                    x: nodeWidth + baseConfig.countWidth * 2,
                                    y: 20,
                                },
                            });

                            // 延伸线
                            const lineLongth =
                                nodeWidth + baseConfig.countWidth + (children && children.length ? 0 : 14);

                            group.addShape('path', {
                                attrs: {
                                    path: [
                                        ['M', nodeWidth, height / 2],
                                        ['L', nodeWidth + baseConfig.countWidth, height / 2],
                                    ],
                                    stroke: '#AAB7C4',
                                    lineWidth: 1,
                                    opacity: 1
                                },
                                name: 'node-path-shape',
                            });

                        }
                        return keyShape;
                    },
                    /**
                     * 更新节点，包含文本
                     * @override
                     * @param  {Object} cfg 节点的配置项
                     * @param  {Node} node 节点
                     */
                    update(cfg, node) {},
                    /**
                     * 设置节点的状态，主要是交互状态，业务状态请在 draw 方法中实现
                     * 单图形的节点仅考虑 selected、active 状态，有其他状态需求的用户自己复写这个方法
                     * @param  {String} name 状态名称
                     * @param  {Object} value 状态值
                     * @param  {Node} node 节点
                     */
                    setState(name, value, node) {},
                },
                'extendedNodeName',
            )
        },
        registerEdge() {
            registerEdge('smoothEdge', {
                draw(cfg, group) {
                    const { startPoint, endPoint } = cfg;
                    const hgap = endPoint.x + baseConfig.countWidth - startPoint.x;
                    const path = [
                        ['M', startPoint.x + baseConfig.countWidth * 3.3, startPoint.y],
                        [
                            'C',
                            startPoint.x + hgap / 4,
                            startPoint.y,
                            endPoint.x - hgap / 2,
                            endPoint.y,
                            endPoint.x,
                            endPoint.y,
                        ],
                    ];

                    const shape = group.addShape('path', {
                        attrs: {
                            path,
                            stroke: '#AAB7C4',
                            lineWidth: 2
                        },
                    });

                    return shape;
                },
                getLabelStyle(cfg) {
                    // 根据业务返回 label 的样式
                    return {
                        color: 'red'
                    };
                }
            });
        }
    }

    const graphMenuCallBack = {
        setToRoot(item) {
            const { Recid } = item.getModel();
            const nodes = utils.findById(Recid, mockData);

            treeGraph.changeData(nodes);
            treeGraph.fitCenter();
        },
        appendItem(item) {
            var model = item.getModel();
            var id = utils.generateNodeId();
            const cfg = {
                id,
                label: '新节点',
                Depth: model.Depth + 1,
                WorkContent: '新节点',
                children: [],
            };

            treeGraph.addChild(cfg, model.id);
        },
        // 删除节点和边
        deleteItem(item) {
            const { id } = item.getModel();

            if (window.confirm('确定要删除该节点吗? 此操作不可撤销!')) {
                const matrix = treeGraph.get('group').getMatrix();

                treeGraph.set('animate', false);
                treeGraph.removeChild(id);
                treeGraph.get('group').setMatrix(matrix);
                treeGraph.set('animate', true);
            }
        }
    };

    const toolbarCallBack = {
        defaultSize() {
            treeGraph.zoomTo(1);
        },
        // 缩小
        zoomOut() {
            treeGraph.zoom(0.9);
        },
        // 放大
        zoomIn() {
            treeGraph.zoom(1.1);
        },
        relocation() {
            treeGraph.moveTo(100, 90);
        },
        graphHelp() {
            vue.showHelper = true;
        },
    };

    const utils = {
        findById(Recid, treeData) {
            if (!treeData) return;
            // 深度优先查找
            const { children } = treeData;

            if (treeData.Recid === Recid) {
                return treeData;
            } else if (children && children.length) {
                for (let i = 0; i < children.length; i++) {
                    if (children[i].Recid === Recid) {
                        return children[i];
                    } else {
                        const nodes = this.findById(Recid, children[i]);

                        if (nodes) {
                            return nodes;
                        }
                    }
                }
            }
        },
        generateNodeId() {
            return `${+new Date() + (Math.random() * 10e5).toFixed(0)}`;
        }
    };


    createGraph.init();
    // treeGraph.data(mockData);
    // treeGraph.render();
    treeGraph.read(mockData);
    treeGraph.fitCenter();
    treeGraph.fitView();
    // 为图上的所有节点绑定点击监听
    treeGraph.on('node:click', (evt) => {
        console.log(1);
        // const model = evt.item.getModel(); // 被操作的节点 item
        // if (!vue.switchValue) return;
        // OpenFirst(model.Depth, evt);
    });

    treeGraph.on('node:dblclick', (evt) => {
        console.log(2);
        const model = evt.item.getModel(); // 被操作的节点 item
        if (!vue.switchValue) return;
        OpenFirst(model.Depth, evt);
        // if (model.Depth == 0) {
        //     vue.firstDialog = true;
        // } else if (model.Depth == 1) {
        //     vue.secondDialog = true;
        // } else if (model.Depth == 2) {
        //     vue.thirdDialog = true;
        // } else if (model.Depth == 3) {
        //     vue.fourthDialog = true;
        // }
    });
    treeGraph.setMode('edit');

})